/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This class handles web service calls associated with title information.
 * 
 */

package us.in.lib.acpl.Mobile_ACPL.ws;

import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Xml;
import us.in.lib.acpl.Mobile_ACPL.SearchResultsTitleDetailActivity;
import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.item.AvailabilityInfo;
import us.in.lib.acpl.Mobile_ACPL.item.CallInfo;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient.RequestMethod;

public class ItemDetailHandler {

    //ACPL: Removed Sirsi and Syndetics URLs
	public static final String WS_URL = Mobile_ACPL.WS_HOST+"";
	public static final String URL_START = "";
	public static final String IMAGE_URL_END = "";
	public static final String SUMMARY_URL_END = "";
	public static final String AUTHOR_NOTES_URL_END = "";
	public static final String LJ_REVIEW_URL_END = "";
	public static final String PW_REVIEW_URL_END = "";

	private SearchResultsTitleDetailActivity act;
	private String isbn;
	private String titleID;
	private String title;
	private String author;
	private String materialType;

	public ItemDetailHandler(SearchResultsTitleDetailActivity act, String isbn,
			String titleID, String title, String author, String materialType) {
		this.materialType = materialType;
		this.act = act;
		this.isbn = isbn;
		this.title = title;
		this.author = author;
		this.titleID = titleID;
	}

	public void getCoverImage() {
		new GetCoverImageTask().execute();
	}

	public void getSummary() {
		new GetSummaryTask().execute();
	}

	public void getItemAvailabilityInfo() {
		new GetItemAvailabilityInfoTask().execute();
	}

	public void getAuthorNotes() {
		new GetAuthorNotesTask().execute();
	}

	private class GetCoverImageTask extends AsyncTask<Void, Void, Bitmap> {

		@Override
		protected Bitmap doInBackground(Void... args) {

			Bitmap coverImage = null;

			try {
				URL newurl = new URL(URL_START + isbn + IMAGE_URL_END);
				coverImage = BitmapFactory.decodeStream(newurl.openConnection()
						.getInputStream());
				// setImage(coverImage);

			} catch (Exception e) {
				e.printStackTrace();
			}

			return coverImage;
		}

		@Override
		protected void onPostExecute(Bitmap image) {
			act.setImage(image);
		}

	}

	private class GetSummaryTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			// Create a rest client to handle the request
			RestClient client = new RestClient(URL_START + isbn
					+ SUMMARY_URL_END);

			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {

				e.printStackTrace();
			}

			String response = client.getResponse();

			String summary = null;

			// Parse the summary out of the XML response
			if (response != null) {
				try {

					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(new StringReader(response));

					int eventType = parser.getEventType();

					while (eventType != XmlPullParser.END_DOCUMENT) {
						if (eventType == XmlPullParser.START_TAG) {
							if (parser.getName().equalsIgnoreCase("Notes")) {
								parser.next();
								parser.next();
								summary = parser.nextText();
								break;
							}
						}
						eventType = parser.next();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// Display this message when no summary is returned.
			if (summary == null) {
				summary = "Not available for this title.";
			}

			return summary;
		}

		@Override
		protected void onPostExecute(String summary) {

			act.setSummaryText(summary);
		}
	}

	private class GetItemAvailabilityInfoTask extends
			AsyncTask<String, Void, List<AvailabilityInfo>> {

		@Override
		protected List<AvailabilityInfo> doInBackground(String... params) {
			RestClient client = new RestClient(WS_URL);
			client.AddHeader("x-sirs-clientID", SearchCatalogHandler.CLIENT_ID);
			client.AddParam("titleID", titleID);
			client.AddParam("includeAvailabilityInfo", "true");
			client.AddParam("includeItemInfo", "true");

			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {

				e.printStackTrace();
			}

			String response = client.getResponse();

			// Parse the CallInfo from the response

			HashMap<String, AvailabilityInfo> availMap = new HashMap<String, AvailabilityInfo>();

			if (response != null) {
				AvailabilityInfo currAvail = new AvailabilityInfo();
				CallInfo currCall = new CallInfo();
				HashMap<String, Integer> map = new HashMap<String, Integer>();
				try {
					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(new StringReader(response));

					int eventType = parser.getEventType();
					while (eventType != XmlPullParser.END_DOCUMENT) {
						if (eventType == XmlPullParser.END_TAG) {
							if (parser.getName().equalsIgnoreCase("CallInfo")) {

								currCall.setCopyLocations(map);
								map = new HashMap<String, Integer>();

								currAvail.addCallInfo(currCall);
								currCall = new CallInfo();
							}
						}
						if (eventType == XmlPullParser.START_TAG) {
							String name = parser.getName();
							if (name.equalsIgnoreCase("libraryID")) {
								String library = parser.nextText();
								currAvail = availMap.get(library);
								if (currAvail == null) {
									currAvail = new AvailabilityInfo();
									currAvail.setLibrary(library);
									availMap.put(library, currAvail);
								}
							}
							if (name.equalsIgnoreCase("callNumber")) {
								currCall.setCallNumber(parser.nextText());
							}
							if (name.equalsIgnoreCase("numberOfCopies")) {
								currCall.setNumCopies(parser.nextText());
							}
							if (name.equalsIgnoreCase("currentLocationID")) {
								String loc = parser.nextText();
								Integer value = map.get(loc);

								if (value == null) {
									map.put(loc, 1);
								} else {
									map.put(loc, value.intValue() + 1);
								}
							}

						}

						eventType = parser.next();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return new ArrayList<AvailabilityInfo>(availMap.values());

		}

		@Override
		protected void onPostExecute(List<AvailabilityInfo> list) {
			act.displayItemAvailabilityInfo(list);
		}
	}

	private class GetAuthorNotesTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			// Create a rest client to handle the request
			RestClient client = new RestClient(URL_START + isbn
					+ AUTHOR_NOTES_URL_END);

			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {

				e.printStackTrace();
			}

			String response = client.getResponse();

			String authorNotes = null;

			if (response != null) {
				// Parse the summary out of the XML response
				try {

					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(new StringReader(response));

					int eventType = parser.getEventType();

					while (eventType != XmlPullParser.END_DOCUMENT) {
						if (eventType == XmlPullParser.START_TAG) {
							if (parser.getName().equalsIgnoreCase("SSIFLDS")) {
								parser.next();
								parser.next();
								parser.next();
								parser.next();
								authorNotes = parser.nextText();
								break;
							}
						}
						eventType = parser.next();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// Display this message when no summary is returned.
			if (authorNotes == null) {
				authorNotes = "Not available for this title.";
			}

			return authorNotes;
		}

		@Override
		protected void onPostExecute(String authorNotes) {

			act.setAuthorNotes(authorNotes);
		}
	}

}
